import { Component, Vue, Watch } from 'vue-property-decorator'
import { Action } from 'vuex-class'
import { desensitization } from '@/lib/utils'
import styles from './PaymentOrder.less'
import OperationCol from '@/components/OperationCol'
import AddressLayer from '@/modules/addressLayer'
import InvoiceInfo from './InvoiceInfo'
import RadioGroup from '../radioGroup/RadioGroup'
import { cacheOrder, getCacheOrder } from '@/lib/cache'

import {
  adminTypes,
  formatStatus,
  orgLicenseTypes,
  orgTypes,
  useTypes,
  userLicenseTypes,
  sealTypes,
  IStatus,
  payTypes,
  expressPayTypes,
  sealUseTimes,
} from '@/lib/sealFormat'

export interface IGoods {
  goodsType: number
  price: string
  quantity: number
  externalOrderId?: string
  label?: string
}

const formLabelWidth6: string = '96px'
const formLabelWidth7: string = '116px'

const detailData: any[] = [
  {
    key: 'eSealBasicInfo',
    title: '电子印章基本信息',
    single: true,
    child: [
      // { key: "sealCode", colLength: 12, labelWidth: formLabelWidth7, label: "印章编码", content: "" },
      {
        key: 'sealUseTypeName',
        colLength: 12,
        labelWidth: formLabelWidth7,
        label: '用章方式',
        content: '',
      },
      {
        key: 'sealName',
        colLength: 12,
        labelWidth: formLabelWidth6,
        label: '电子印章名称',
        content: '',
      },
      {
        key: 'sealUseTimeName',
        colLength: 12,
        labelWidth: formLabelWidth7,
        label: '有效期',
        content: '',
        tips:
          '本系统制作的电子印章按年收费（¥280/年），有效期为1至5年。自印章制作完成后开始计算有效期，有效期满时需进入本系统申请延期后方可继续使用。',
      },
      {
        key: 'sealTypeName',
        colLength: 12,
        labelWidth: formLabelWidth6,
        label: '电子印章类别',
        content: '',
      },
    ],
  },
  {
    key: 'sealOrgBasicInfo',
    title: '用章机构基本信息',
    child: [
      {
        key: 'applyOrganizeName',
        label: '机构名称',
        labelWidth: formLabelWidth7,
        content: '',
      },
      {
        key: 'applyOrganizeType',
        label: '机构类型',
        labelWidth: formLabelWidth6,
        content: '',
      },
      {
        key: 'applyOrganizeLicenseType',
        label: '证照类型',
        labelWidth: formLabelWidth7,
        content: '',
      },
      {
        key: 'applyOrganizeLicenseNumber',
        label: '证照号码',
        labelWidth: formLabelWidth6,
        content: '',
      },
      // { key: "organizeLevel", label: "行政等级", labelWidth: formLabelWidth3, content: "" }
    ],
  },
]

const receiver = {
  id: '',
  consigneeName: '',
  provinceName: '',
  cityName: '',
  areaName: '',
  areaDetail: '',
  consigneeMobile: '',
}

const amountList: any[] = [
  { label: '电子印章年服务费：', key: 1 },
  { label: 'Ukey硬件介质：', key: 2 },
  { label: '快递费：', key: 4 },
]
@Component({})
export default class PaymentOrder extends Vue {
  private detailData: any[] = []
  private sealUrl: string = ''
  private orderInfo: any = {
    payType: 0,
    expressPayType: 0,
  }
  private orderPayTypes: any[] = []
  private orderInfoList: any[] = []
  private amountList: any[] = []
  private useType = 1 // 用章方式
  private sealUseType: number = 0
  private isAll: boolean = false
  private sealApplyId?: any = ''
  private defaultData: any = {}
  private invoiceVisible: boolean = false
  private addressShow: boolean = false
  private addressData: any = {}
  private addible: number = 0 // 是否可新增
  private canPay: boolean = false
  private receiverList: any[] = []
  private receiver: any = null
  private hoverId = ''
  private invoiceInfo = {
    name: '增值税电子普通发票',
    type: '电子发票',
    orgName: '',
    orgCode: '',
    id: 0,
  }
  private invoiceInfoWarning = ''
  private selectPayOrganize: string = ''
  private selectPayOrganizeInfo: any = {}
  private payOrganizeInfos: any[] = []
  private loading: boolean = false
  private oldOrderId: number = 0
  private loaded: boolean = false
  private realPayerOrganizeContactPhone: string = ''

  @Action('newApply/sealDetail') private sealDetail!: any
  @Action('newApply/checkSealNameRepeat') private checkSealNameRepeat!: any
  @Action('paymentOrder/querySealApplyPayPreOrderInfo')
  private querySealApplyPayPreOrderInfo!: any
  @Action('paymentOrder/listMyDeliveryAddress')
  private listMyDeliveryAddress!: any
  @Action('paymentOrder/setAddressAsDefault') private setAddressAsDefault!: any
  @Action('paymentOrder/deleteDeliveryAddress')
  private deleteDeliveryAddress!: any
  @Action('applyPage/createOrder') private createOrder!: any
  @Action('user/payOrganizeDataMasking') private payOrganizeDataMasking!: any

  @Watch('orderInfo.payType')
  private payTypeChange(type: number) {
    this.orderInfo.expressPayType =
      this.orderInfo.payType === 2 ? 0 : this.orderInfo.expressPayType || 1
  }

  renderDetail(detail: any) {
    return (
      <div class={styles.orderDetailItem}>
        <h5>{detail.title}</h5>
        <el-row>
          {detail.child &&
            detail.child.map((item: any) => (
              <el-col
                class={styles.orderDetailItemCol}
                span={item.colLength || 12}
              >
                <label class={styles.orderDetailItemLabel}>
                  {item.label || ''}:
                </label>
                <div class={styles.orderDetailItemContent}>
                  {item.content || ''}
                  {item.tips && (
                    <el-tooltip placement="bottom-start">
                      <p slot="content">{item.tips}</p>
                      <i class="el-icon-info ml10" />
                    </el-tooltip>
                  )}
                </div>
              </el-col>
            ))}
        </el-row>
      </div>
    )
  }

  payTypesRadioRender(item: IStatus) {
    return (
      <div class={styles.payTypeRadio}>
        <h6>{item.value}</h6>
        <p>{item.intro}</p>
      </div>
    )
  }

  invioceInfoRender() {
    return (
      <div class={styles.invoicesTable}>
        <p class={styles.title}>{this.invoiceInfo.name}</p>
        <div class={styles.content}>
          <p class={styles.label}>发票抬头</p>
          <p class={styles.mark}>：</p>
          <p class={styles.value}>{this.invoiceInfo.orgName}</p>
        </div>
        <div class={styles.content}>
          <p class={styles.label}>统一社会信用代码</p>
          <p class={styles.mark}>：</p>
          <p class={styles.value}>{this.invoiceInfo.orgCode}</p>
        </div>
      </div>
    )
  }

  protected render(h: any) {
    // console.log('payType:',this.orderInfo.payType)
    return (
      <div>
        <div class={styles.payOrder} v-loading={this.loaded}>
          {this.detailData &&
            this.detailData.map((item: any, index: number) =>
              this.renderDetail(item)
            )}

          <div class={styles.inputForm}>
            <p class={styles.panel}>付费方式</p>
            <RadioGroup
              showIntro={false}
              value={this.orderInfo.payType}
              {...{
                on: {
                  'update:value': (val: any) => {
                    this.orderInfo.payType = val
                  },
                },
              }}
              radioRender={this.payTypesRadioRender}
              data={payTypes.filter((item: IStatus) => {
                return this.orderPayTypes.includes(item.id)
              })}
            />
            {/* <el-radio-group v-model={this.orderInfo.payType} onChange={this.payTypeChange}>
							{payTypes &&
								payTypes.map((item: IStatus, i: number) => {
									if (this.orderPayTypes.includes(item.id)) {
										return <el-radio label={item.id}>{item.value}</el-radio>;
									}
								})}
						</el-radio-group> */}
            {this.orderInfo.payType === 2 && (
              <span>
                <p class={styles.panel}>统一付费方信息</p>
                <p class={styles.invoices}>
                  统一付费方：
                  <el-select
                    v-model={this.selectPayOrganize}
                    placeholder="请选择"
                    onChange={this.selectPayOrganizeChange}
                  >
                    {this.payOrganizeInfos.map((item: any) => {
                      return (
                        <el-option
                          key={item.payerOrganizeUUID}
                          label={item.payerOrganizeName}
                          value={item.payerOrganizeUUID}
                        />
                      )
                    })}
                  </el-select>
                  付费方管理员：
                  {this.selectPayOrganizeInfo.payerOrganizeContactName || ''}
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  {this.realPayerOrganizeContactPhone ? (
                    <span>{this.realPayerOrganizeContactPhone}</span>
                  ) : (
                    <span>
                      {desensitization(
                        this.selectPayOrganizeInfo.payerOrganizeContactPhone
                      )}
                      {!!this.selectPayOrganizeInfo
                        .payerOrganizeContactPhone && (
                        <el-button
                          type="text"
                          style="padding:0;min-width:60px;"
                          onClick={this.showRealPhone}
                        >
                          点击查看
                        </el-button>
                      )}
                    </span>
                  )}
                </p>
              </span>
            )}
            <div>
              {this.defaultData.sealUseType === 1 && (
                <h2 class={styles.panel}>送货清单</h2>
              )}
              {this.orderInfo.payType === 1 && this.sealUseType === 1 && (
                <div>
                  <div class={styles.subTitle}>快递费用支付方式</div>
                  <div>
                    <RadioGroup
                      style="display:inline-block;"
                      showIntro={false}
                      value={this.orderInfo.expressPayType}
                      {...{
                        on: {
                          'update:value': (val: any) => {
                            this.orderInfo.expressPayType = val
                          },
                        },
                      }}
                      radioRender={this.payTypesRadioRender}
                      data={expressPayTypes}
                    />
                    <span class={styles.expressTypeTip}>
                      选择快递到付后，订单中不包含快递费内容，其他物流信息正常执行。
                    </span>
                  </div>
                </div>
              )}
            </div>
            {this.defaultData.sealUseType === 1 && (
              <div class={styles.shippingAddressArea}>
                <p class={styles.subTitle}>
                  UKey收货人信息
                  {this.orderInfo.payType === 1 && (
                    <el-button
                      class="ml10"
                      type="text"
                      onClick={this.addAddress}
                    >
                      新增收货地址
                    </el-button>
                  )}
                </p>
                {this.orderInfo.payType === 1 ? (
                  <div>
                    <el-table
                      class={styles.receiver}
                      data={
                        this.isAll
                          ? this.receiverList
                          : this.receiver
                          ? [this.receiver]
                          : []
                      }
                      style="width: 100%;"
                      show-header={false}
                      onCell-mouse-enter={(row: any) => {
                        this.hoverId = row.id
                      }}
                      onCell-mouse-leave={(row: any) => {
                        this.hoverId = ''
                      }}
                      onRow-click={this.selectRow}
                    >
                      <div slot="empty">
                        <p>暂无收货地址</p>
                      </div>
                      <el-table-column
                        width="30"
                        {...{
                          scopedSlots: {
                            default: (scope: any) => {
                              return (
                                <el-radio-group v-model={this.receiver}>
                                  <el-radio label={scope.row} />
                                </el-radio-group>
                              )
                            },
                          },
                        }}
                      />
                      <el-table-column
                        prop="consigneeName"
                        label="姓名"
                        min-width="50"
                        show-overflow-tooltip
                      />
                      <el-table-column
                        prop="id"
                        show-overflow-tooltip
                        min-width="180"
                        {...{
                          scopedSlots: {
                            default: (scope: any) => {
                              return (
                                <span>
                                  {scope.row.provinceName}&nbsp;
                                  {scope.row.cityName}&nbsp;{scope.row.areaName}
                                </span>
                              )
                            },
                          },
                        }}
                      />
                      <el-table-column prop="areaDetail" min-width="360" />
                      <el-table-column
                        prop="consigneeMobile"
                        show-overflow-tooltip
                        min-width="110"
                      />
                      {/* <el-table-column prop="phone" width="100"/> */}
                      <el-table-column
                        prop="id"
                        show-overflow-tooltip
                        {...{
                          scopedSlots: {
                            default: (scope: any) => {
                              if (scope.row.defaultStatus === 1) {
                                return <p class={styles.default}>默认地址</p>
                              }
                            },
                          },
                        }}
                      />
                      <el-table-column
                        prop="operation"
                        label="操作"
                        align="right"
                        width="220"
                        {...{
                          scopedSlots: {
                            default: (scope: any) => {
                              return (
                                <OperationCol
                                  v-show={this.hoverId === scope.row.id}
                                  operations={this.filterOptions(scope.row)}
                                  showNum={4}
                                  row={scope.row}
                                  index={scope.$index}
                                />
                              )
                            },
                          },
                        }}
                      />
                    </el-table>
                    {(this.receiverList || []).length > 1 && (
                      <p class={styles.backup}>
                        {this.isAll ? (
                          <a class="cp mt20" onClick={() => this.backup(false)}>
                            收起地址
                            <i class="el-icon-arrow-up" />
                          </a>
                        ) : (
                          <a class="cp mt20" onClick={() => this.backup(true)}>
                            更多地址
                            <i class="el-icon-arrow-down" />
                          </a>
                        )}
                      </p>
                    )}
                  </div>
                ) : (
                  <div>
                    <p class="info">
                      <i class="el-icon-warning" />
                      UKey硬件介质将会直接邮寄至付费方负责人处。请申请人主动联络付费方负责人，现场领取UKey硬件介质。
                    </p>
                    <div class={{ [styles.invoices]: true, pl20: true }}>
                      <p>
                        <span class={styles.title}>UKey收货人信息：</span>
                        {this.selectPayOrganizeInfo.payerOrganizeContactName}
                      </p>
                      <p>
                        {desensitization(
                          this.selectPayOrganizeInfo.payerOrganizeContactPhone
                        )}
                      </p>
                      <p>
                        <span class={styles.title}>收货地址：</span>
                        {
                          this.selectPayOrganizeInfo
                            .payerOrganizeShippingAddress
                        }
                      </p>
                    </div>
                    <p class="pl20">
                      <span class={styles.title}>详细地址：</span>
                      {this.selectPayOrganizeInfo.payerOrganizeAddressDetail}
                    </p>
                  </div>
                )}
              </div>
            )}
            {this.orderInfo.payType === 1 && (
              <span>
                <p class={styles.panel}>
                  发票信息
                  <el-button type="text" onClick={this.editInvoices}>
                    修改
                  </el-button>
                </p>
                <RadioGroup
                  style="display:inline-block;"
                  class={{
                    [styles.invoicesRadio]: true,
                    [styles.warningRadio]: !!this.invoiceInfoWarning,
                  }}
                  showIntro={false}
                  value={this.invoiceInfo.id}
                  {...{
                    on: {
                      'update:value': (val: any) => {
                        this.invoiceInfo.id = val
                        this.invoiceInfoWarning = ''
                      },
                    },
                  }}
                  radioRender={this.invioceInfoRender}
                  data={[{ ...this.invoiceInfo, id: 1 }]}
                />
                <p class={styles.tips}>
                  <p class={styles.warning}>{this.invoiceInfoWarning}</p>
                  <i class="el-icon-info" />
                  该发票为增值税电子普通发票，请在支付成功后至“我的订单”中申请并下载
                </p>
                {/* {this.invoiceInfo && (
                  <div class={styles.invoices}>
                    <p>{this.invoiceInfo.name}</p>
                    <p>{this.invoiceInfo.type}</p>
                    <p class="org">{this.invoiceInfo.orgName}</p>
                    <p class="w180">{this.invoiceInfo.orgCode}</p>
                  </div>
                )} */}
              </span>
            )}

            <p class={styles.panel}>订单明细</p>
            <div class={styles.orderDetail}>
              <div class={styles.goodsList}>
                <div class={styles.lists}>
                  {this.getPayDetail().map(
                    (amount: any, index: number) =>
                      (amount.goodsType === 1 ||
                        (amount.goodsType === 2 &&
                          this.defaultData.sealUseType === 1) ||
                        (amount.goodsType === 4 &&
                          this.defaultData.sealUseType === 1 &&
                          this.orderInfo.payType === 1)) && (
                        <p class={styles.detail}>
                          <p class={styles.label}>{amount.label}</p>
                          <p
                            class={{
                              [styles.value]: true,
                              [styles.isDiscount]: amount.price === '0.00',
                            }}
                          >
                            <span>
                              ￥
                              {amount.price / amount.quantity
                                ? (amount.price / amount.quantity).toFixed(2)
                                : '35.00'}
                            </span>
                            {amount.price === '0.00' && (
                              <p class={styles.discount}>优惠</p>
                            )}
                          </p>
                          {amount.quantity && amount.goodsType !== 4 && (
                            <p class={styles.number}>x{amount.quantity}</p>
                          )}
                        </p>
                      )
                  )}
                </div>
              </div>
              <div class={styles.amountPart}>
                <p class={styles.amount}>
                  应付总额：
                  <span class={styles.number}>￥{this.getAllAmount()}</span>
                </p>
                {this.defaultData.sealUseType === 1 &&
                  (this.orderInfo.payType === 1 ? (
                    <div class={styles.address}>
                      <p>
                        收货人：{(this.receiver || receiver).consigneeName}
                        &nbsp;&nbsp;
                        {(this.receiver || receiver).consigneeMobile}
                      </p>
                      <p>
                        寄送至：{(this.receiver || receiver).provinceName}&nbsp;
                        {(this.receiver || receiver).cityName}
                        &nbsp;
                        {(this.receiver || receiver).areaName}&nbsp;
                        {(this.receiver || receiver).areaDetail}
                      </p>
                    </div>
                  ) : (
                    <div class={styles.address}>
                      <p>
                        收货人：
                        {this.selectPayOrganizeInfo.payerOrganizeContactName}
                        &nbsp;&nbsp;
                        {desensitization(
                          this.selectPayOrganizeInfo.payerOrganizeContactPhone
                        )}
                      </p>
                      <p>
                        寄送至：
                        {
                          this.selectPayOrganizeInfo
                            .payerOrganizeShippingAddress
                        }
                        &nbsp;
                        {this.selectPayOrganizeInfo.payerOrganizeAddressDetail}
                      </p>
                    </div>
                  ))}
              </div>
            </div>
          </div>
          {/* {this.canPay && this.orderPayTypes.length > 0 && (
						<div class={styles.footer}>
							<el-button onClick={this.notPay}>暂不支付</el-button>
							<el-button type="primary" onClick={this.toPay} loading={this.loading}>
								前往支付
							</el-button>
						</div>
					)} */}
        </div>
        <InvoiceInfo
          visible={this.invoiceVisible}
          defaultData={this.invoiceInfo}
          onVisibleChange={(val: boolean) => {
            this.invoiceVisible = val
          }}
          onSubmit={(val: any) => {
            this.invoiceInfo.orgName = val.orgName
            this.invoiceInfo.orgCode = val.licenseNumber
          }}
        />
        <AddressLayer
          show={this.addressShow}
          {...{
            on: {
              'update:show': (val: boolean) => {
                this.addressShow = val
              },
              'update:data': (val: any) => {
                this.addressData = val
              },
            },
          }}
          data={this.addressData}
          onSuccess={this.addressSuccess}
        />
      </div>
    )
  }

  private async mounted() {
    this.sealApplyId = this.$route.query.id || ''
    this.oldOrderId = parseInt(this.$route.query.orderId as string)
    if (!this.sealApplyId) return
    this.sealApplyId = parseInt(this.sealApplyId)
    this.loaded = true
    await this.getSealDetail()
    // this.detailData = detailData;
    await this.getPreOrder()
    this.loaded = false
    this.getMyAddressList()
    // todo 回显订单信息

    // this.receiver = this.receiverList[0];
    // this.amountList = amountList;
  }

  private async getSealDetail() {
    const oldOrderInfo: any = getCacheOrder(this.oldOrderId) || {}
    await this.sealDetail(this.sealApplyId).then((res: any) => {
      this.canPay = res.sealApplyStatus === 26 // 待支付状态
      this.sealUseType = res.sealUseType
      // this.invoiceInfo.orgName = res.applyOrganizeName;
      // this.invoiceInfo.orgCode = res.applyOrganizeLicenseNumber;
      // 开票信息
      this.invoiceInfo.orgName =
        oldOrderInfo.invoiceTitle || res.applyOrganizeName
      this.invoiceInfo.orgCode =
        oldOrderInfo.taxpayerIdentityNumber || res.applyOrganizeLicenseNumber
      this.defaultData = {
        ...res,
        agentLicenseType: formatStatus(userLicenseTypes, res.agentLicenseType),
        applyOrganizeLevel: formatStatus(adminTypes, res.applyOrganizeLevel),
        applyOrganizeLicenseType: formatStatus(
          orgLicenseTypes,
          res.applyOrganizeLicenseType
        ),
        applyOrganizeType: formatStatus(orgTypes, res.applyOrganizeType),
        confirmOrganizeLicenseType: formatStatus(
          orgLicenseTypes,
          res.confirmOrganizeLicenseType
        ),
        sealTypeName: formatStatus(sealTypes, res.sealType),
        sealUseTypeName: formatStatus(useTypes, res.sealUseType),
        agentLicenseNumberDes: desensitization(res.agentLicenseNumber || ''),
        agentMobileDes: desensitization(res.agentMobile || ''),
        sealUseTimeName: formatStatus(sealUseTimes, res.sealUseTime),
      }
      detailData.forEach((detail: any) => {
        detail.child.forEach((item: any) => {
          item.content = this.defaultData[item.key]
        })
      })
      // console.log(detailData)
      this.detailData = detailData
      /* if (!this.canPay) {
        this.$message.error("当前印章申请不处于待支付状态");
        return
			} */
      // console.log('payOrderId:',res.payOrderId)
      if (!!res.payOrderId) {
        // this.$message.info("订单已存在")
        this.$router.push({
          name: 'orderConfirm',
          query: { orderId: res.payOrderId, sealApplyId: this.sealApplyId },
        })
      }
    })
  }

  private async getPreOrder() {
    const oldOrderInfo: any = getCacheOrder(this.oldOrderId) || {}
    // console.log(oldOrderInfo);
    await this.querySealApplyPayPreOrderInfo(this.sealApplyId).then(
      (res: any) => {
        this.orderPayTypes = []
        this.orderInfoList = res
        /* res.map((order: any) => {
				const goods = (order.goods || []).map((good: any) => {
					return { ...good, ...(amountList.find((amount: any) => amount.key === good.goodsType) || {}) };
				});
				return {
					...order,
					goods
				};
			}); */
        // console.log(this.orderInfoList)

        res.forEach((element: any) => {
          this.orderPayTypes.push(element.payType)
          if (element.payType === 2) {
            this.payOrganizeInfos = this.payOrganizeInfos.concat(
              element.payOrganizeInfos
            )
          }
        })
        // 有统一付费默认选择统一付费
        this.orderInfo.expressPayType = oldOrderInfo.expressPayType || 0
        this.orderInfo.payType =
          oldOrderInfo.payType || (this.orderPayTypes.includes(2) ? 2 : 1)
        // ukey 收货人地址
        if (oldOrderInfo.deliveryAddressId) {
          this.receiver = this.getReceiver(
            oldOrderInfo.deliveryAddressId,
            this.receiverList.length > 0
          )
        }
        // 统一付款方
        if (oldOrderInfo.payerOrganizeUUID && this.orderInfo.payType === 2) {
          this.selectPayOrganizeInfo = this.payOrganizeInfos.find(
            (item: any) =>
              item.payerOrganizeUUID === oldOrderInfo.payerOrganizeUUID
          )
          this.selectPayOrganize = this.selectPayOrganizeInfo.payerOrganizeUUID
        } else {
          this.selectPayOrganize =
            (this.payOrganizeInfos[0] || {}).payerOrganizeUUID || ''
          this.selectPayOrganizeInfo = this.payOrganizeInfos[0] || {}
        }
      }
    )
  }

  /* private payTypeChange(val: number) {} */

  private selectPayOrganizeChange(val: string) {
    this.selectPayOrganizeInfo =
      (this.payOrganizeInfos || []).find(e => e.payerOrganizeUUID === val) || {}
  }

  private selectRow(row: any, column: any) {
    if (
      column.property !== 'operation' &&
      (this.receiver || { id: '' }).id !== row.id
    ) {
      // 操作点击不选中&&选中之前的不触发backup
      this.receiver = row
      this.backup(false)
      this.hoverId = ''
      this.sortReceiverList()
    }
  }

  private sortReceiverList() {
    // 排序收货人地址信息
    this.receiverList = [this.receiver].concat(
      (this.receiverList || [])
        .filter(item => item.id !== (this.receiver || { id: '' }).id)
        .sort((a: any, b: any) => b.defaultStatus - a.defaultStatus)
    )
  }

  private backup(isAll: boolean) {
    this.isAll = isAll
    if (isAll) {
      this.getMyAddressList()
    }
  }

  private notPay() {
    this.$router.back()
  }

  toPay() {
    // console.log('toPay')

    // 检查印章名称是否重复
    return new Promise((resolve, reject) => {
      if (
        this.defaultData.sealUseType === 1 &&
        this.orderInfo.payType === 1 &&
        !(this.receiver || { id: '' }).id
      ) {
        // UKEY自付费未选中收货地址
        this.$message.warning('请选择收货人信息及收货地址')
        reject()

        return
      }

      if (this.orderInfo.payType === 2 && !this.selectPayOrganize) {
        // 统一付费方判断
        this.$message.warning('请选择统一付费方')
        reject()

        return
      }

      if (
        this.orderInfo.payType === 1 &&
        (!this.invoiceInfo.orgName || !this.invoiceInfo.orgCode)
      ) {
        // 自付费发票信息判断
        this.$message.warning('请完善发票信息')
        reject()

        return
      }
      if (this.orderInfo.payType === 1 && !this.invoiceInfo.id) {
        this.$message.warning('请检查发票信息并进行勾选确认')
        this.invoiceInfoWarning = '请检查发票信息并进行勾选确认'
        reject()

        return
      }

      this.loading = true
      const order = {
        sealApplyId: this.sealApplyId,
        deliveryAddressId:
          this.defaultData.sealUseType === 1 && this.orderInfo.payType === 1
            ? (this.receiver || { id: '' }).id
            : undefined,
        expressFee: (
          this.getPayDetail().find((item: IGoods) => item.goodsType === 4) || {
            price: 0,
          }
        ).price,
        invoiceTitle:
          this.orderInfo.payType === 1 ? this.invoiceInfo.orgName : undefined,
        taxpayerIdentityNumber:
          this.orderInfo.payType === 1
            ? (this.invoiceInfo.orgCode || '').toLocaleUpperCase()
            : undefined,
        payType: this.orderInfo.payType,
        payerOrganizeUUID:
          this.orderInfo.payType === 2
            ? this.selectPayOrganize
            : this.defaultData.applyOrganizeUuid,
        expressPayType:
          this.sealUseType === 1 ? this.orderInfo.expressPayType : 0,
      }
      this.checkSealNameRepeat({ sealApplyId: this.sealApplyId }).then(
        (res: any) => {
          if (!res.data.checkStatus) {
            this.$message.error('印章名称已被使用')
            reject()

            return
          }
          this.createOrder(order)
            .then((res: any) => {
              cacheOrder(res.payOrderId, order)
              // console.log(res,order)
              // this.$message.success("支付成功")
              this.$router.replace({
                name: 'orderConfirm',
                query: {
                  orderId: res.payOrderId,
                  sealApplyId: this.sealApplyId,
                },
              })
            })
            .catch((e: any) => {
              reject()
            })
        }
      )
    })
  }

  get operations() {
    const btns: any[] = [
      {
        id: 1,
        text: '设为默认地址',
        onClick: (index: number, rows: any, e: any) => {
          this.setAddressAsDefault({ id: rows.id }).then((res: any) => {
            this.$message.success('设置成功')
            this.getMyAddressList()
          })
        },
      },
      {
        id: 2,
        text: '修改',
        onClick: (index: number, rows: any) => {
          this.updateAddress(rows)
        },
      },
      {
        id: 3,
        text: '删除',
        onClick: (index: number, rows: any) => {
          this.$confirm(
            '是否确认进行此操作，您将无法恢复这些数据',
            '确认删除',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              customClass: 'confirm-dialog',
              type: 'warning',
            }
          )
            .then(() => {
              this.deleteDeliveryAddress({ id: rows.id }).then((res: any) => {
                this.$message({
                  type: 'success',
                  message: '删除成功',
                })
                this.getMyAddressList()
              })
            })
            .catch(() => {})
        },
      },
    ]

    return btns
  }

  private getPayDetail(): IGoods[] {
    const payInfo = this.getOrderPayInfo()

    return (payInfo.goods || []).map((good: IGoods) => {
      return {
        ...good,
        ...(amountList.find((amount: any) => amount.key === good.goodsType) ||
          {}),
      }
    })
  }

  /**
   *
   * @param data 地址信息，可以为空，添加时会传入
   */
  private getMyAddressList(data?: any) {
    return new Promise((resolve, reject) => {
      this.listMyDeliveryAddress()
        .then((res: any) => {
          this.receiverList = res.list
          // this.addible = res.addible;
          if (!this.receiver) {
            this.receiver = this.receiverList[0] || null
          } else {
            if (data) {
              // 让新添加的地址默认选中
              // 当列表中的地址信息，地区代码与地址详情相同时
              this.receiver = this.receiverList.find(
                item =>
                  item.consigneeName === data.consigneeName &&
                  item.fullCode === data.fullCode &&
                  item.areaDetail === data.areaDetail
              )
            } else {
              // this.receiver = this.receiverList.find(e => e.id === (this.receiver || { id: "" }).id) || null;
              this.receiver = this.getReceiver(this.receiver.id)
            }
          }
          this.sortReceiverList()
          resolve()
        })
        .catch((e: any) => {
          reject()
        })
    })
  }

  /*
   * 获取地址，没有时用默认地址
   * @flag {boolean} 是否返回默认地址
   * */
  getReceiver(deliveryAddressId: number | undefined, flag: boolean = true) {
    const rec =
      this.receiverList.length > 0
        ? this.receiverList.find(e => e.id === deliveryAddressId)
        : null

    return rec || (flag ? this.receiverList[0] : { id: deliveryAddressId })
  }

  private getAllAmount() {
    const payInfo = this.getOrderPayInfo()

    return (payInfo || {}).payAmount || 0
  }

  getOrderPayInfo() {
    const { payType, expressPayType } = this.orderInfo
    const order = this.orderInfoList.find(e => e.payType === payType) || {}

    return (
      (order.expressPayTypeOrderInfos || []).find(
        (item: any) => item.expressPayType === expressPayType
      ) || {}
    )
  }

  private filterOptions(row: any) {
    if (row.defaultStatus === 1) {
      // 默认只能修改
      return [this.operations[1]]
    }
    if (row.id === (this.receiver || { id: '' }).id) {
      // 选中的不能删除
      return [this.operations[0], this.operations[1]]
    }

    return this.operations
  }

  private editInvoices() {
    this.invoiceVisible = true
  }

  private addressSuccess(val: any) {
    console.log(val)
    this.getMyAddressList(val)
  }

  private addAddress() {
    this.addressData = {}
    this.addressShow = true
  }

  private updateAddress(row: any) {
    this.addressData = row
    this.addressShow = true
  }

  private showRealPhone() {
    if (this.selectPayOrganizeInfo) {
      this.payOrganizeDataMasking({
        uuid: this.selectPayOrganizeInfo.payerOrganizeUUID,
      }).then((res: any) => {
        this.realPayerOrganizeContactPhone = res.data.contactPhone
      })
    }
  }
}
